/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pl.put.dcs_modeler.wizards.newComputingObject;

import java.awt.Component;
import java.io.IOException;
import java.io.OutputStream;
import java.util.LinkedHashSet;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.Vector;
import javax.swing.JComponent;
import javax.swing.event.ChangeListener;
import org.netbeans.api.project.Project;
import org.netbeans.api.project.ProjectInformation;
import org.netbeans.api.project.ProjectUtils;
import org.openide.WizardDescriptor;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.filesystems.Repository;
import pl.put.dcs.core.utils.serializer.SerializeManager;
import pl.put.model.computingObject.ComputingObject;

public final class NewComputingObjectWizardIterator implements WizardDescriptor.InstantiatingIterator
{

    private int index;
    private WizardDescriptor wizard;
    private WizardDescriptor.Panel[] panels;

    /**
     * Initialize panels representing individual wizard's steps and sets
     * various properties for them influencing wizard appearance.
     */
    private WizardDescriptor.Panel[] getPanels()
    {
        //Project p = (Project)Lookup.getDefault().lookup( Project.class );
        //System.out.print( p.getProjectDirectory().getPath() );
        if ( panels == null )
        {
            panels = new WizardDescriptor.Panel[]
                    {
                        new NewComputingObjectWizardPanel1(),
                        new NewComputingObjectWizardPanel2(),
                        new NewComputingObjectWizardPanel3()
                    };
            String[] steps = createSteps();
            for ( int i = 0; i < panels.length; i++ )
            {
                Component c = panels[i].getComponent();
                if ( steps[i] == null )
                {
                    // Default step name to component name of panel. Mainly
                    // useful for getting the name of the target chooser to
                    // appear in the list of steps.
                    steps[i] = c.getName();
                }
                if ( c instanceof JComponent )
                { // assume Swing components
                    JComponent jc = ( JComponent ) c;
                    // Sets step number of a component
                    jc.putClientProperty( "WizardPanel_contentSelectedIndex", new Integer( i ) );
                    // Sets steps names for a panel
                    jc.putClientProperty( "WizardPanel_contentData", steps );
                    // Turn on subtitle creation on each step
                    jc.putClientProperty( "WizardPanel_autoWizardStyle", Boolean.TRUE );
                    // Show steps on the left side with the image on the background
                    jc.putClientProperty( "WizardPanel_contentDisplayed", Boolean.TRUE );
                    // Turn on numbering of all steps
                    jc.putClientProperty( "WizardPanel_contentNumbered", Boolean.TRUE );
                }
            }
        }
        return panels;
    }

    @Override
    public Set instantiate() throws IOException
    {
        Project project = ( Project )wizard.getProperty( "project" );
        String objectName = ( String )wizard.getProperty( "objectName" );
        Vector< Vector< String > > inPins = ( Vector )wizard.getProperty( "inPins" );
        Vector< Vector< String > > outPins = ( Vector )wizard.getProperty( "outPins" );
        ComputingObject compObj = new ComputingObject();
        compObj.setName( objectName );
        // towrzenie instancji obiektu ComputingModel. Zmapowanie otrzymanego wektora na obiekt
        for ( Vector tmp : inPins )
        {
            compObj.addPinIn( ( String )tmp.elementAt( 0 ), ( String )tmp.elementAt( 1 ) );
        }

        for ( Vector tmp : outPins )
        {
            compObj.addPinOut( ( String )tmp.elementAt( 0 ), ( String )tmp.elementAt( 1 ) );
        }
       // XStream xStream = new XStream();
        String projectDir = project.getProjectDirectory().getPath();
        FileObject projectRsrc = Repository.getDefault().getDefaultFileSystem().findResource( "Templates/Project/DCS/DCS Project" );
        String defaultProjectPkg = ( String )projectRsrc.getAttribute( "defaultProjectSrcPackage" );
        ProjectInformation projectInfo = ProjectUtils.getInformation( project );

        // pozyskanie ptrzebnych danych
        String projectName = projectInfo.getName();
        FileObject temp = Repository.getDefault().getDefaultFileSystem().findResource( "Templates/DCS/newComputingObject" );
        String pathToCO = "src/" + defaultProjectPkg + "/" + projectName + "/" + ( String )temp.getAttribute( "defaultPackage" ) ;


        FileObject fo = FileUtil.createFolder( project.getProjectDirectory(), pathToCO );
        FileObject file = FileUtil.createData( fo, objectName + ".dcsco" );
        SerializeManager sm = new SerializeManager();
        sm.init();
        OutputStream  os = file.getOutputStream();
        sm.serializeToFile( compObj, os );
        os.close();
        /*FileObject fo = FileUtil.createData( project.getProjectDirectory(), "resources/computingObjects" + objectName + ".xml" );
        OutputStream out = fo.getOutputStream();
        ObjectOutputStream oos = xStream.createObjectOutputStream( out );
        oos.writeObject( compObj ); */
        Set<FileObject> resultSet = new LinkedHashSet<FileObject>();
        //FileObject createdObj = FileUtil.createData( fo, objectName + ".dcsco" );
        //resultSet.add( file );
        return resultSet;
    }

    @Override
    public void initialize( WizardDescriptor wizard )
    {
        this.wizard = wizard;
        getPanels();
    }

    @Override
    public void uninitialize( WizardDescriptor wizard )
    {
        panels = null;
        
    }

    public WizardDescriptor.Panel current()
    {
        return getPanels()[index];
    }

    public String name()
    {
        return index + 1 + ". from " + getPanels().length;
    }

    public boolean hasNext()
    {
        return index < getPanels().length - 1;
    }

    public boolean hasPrevious()
    {
        return index > 0;
    }

    public void nextPanel()
    {
        if ( !hasNext() )
        {
            throw new NoSuchElementException();
        }
        index++;
    }

    public void previousPanel()
    {
        if ( !hasPrevious() )
        {
            throw new NoSuchElementException();
        }
        index--;
    }

    // If nothing unusual changes in the middle of the wizard, simply:
    public void addChangeListener( ChangeListener l )
    {
    }

    public void removeChangeListener( ChangeListener l )
    {
    }

    // If something changes dynamically (besides moving between panels), e.g.
    // the number of panels changes in response to user input, then uncomment
    // the following and call when needed: fireChangeEvent();
    /*
    private Set<ChangeListener> listeners = new HashSet<ChangeListener>(1); // or can use ChangeSupport in NB 6.0
    public final void addChangeListener(ChangeListener l) {
    synchronized (listeners) {
    listeners.add(l);
    }
    }
    public final void removeChangeListener(ChangeListener l) {
    synchronized (listeners) {
    listeners.remove(l);
    }
    }
    protected final void fireChangeEvent() {
    Iterator<ChangeListener> it;
    synchronized (listeners) {
    it = new HashSet<ChangeListener>(listeners).iterator();
    }
    ChangeEvent ev = new ChangeEvent(this);
    while (it.hasNext()) {
    it.next().stateChanged(ev);
    }
    }
     */    // You could safely ignore this method. Is is here to keep steps which were
    // there before this wizard was instantiated. It should be better handled
    // by NetBeans Wizard API itself rather than needed to be implemented by a
    // client code.
    private String[] createSteps()
    {
        String[] beforeSteps = null;
        Object prop = wizard.getProperty( "WizardPanel_contentData" );
        if ( prop != null && prop instanceof String[] )
        {
            beforeSteps = ( String[] ) prop;
        }

        if ( beforeSteps == null )
        {
            beforeSteps = new String[ 0 ];
        }

        String[] res = new String[ (beforeSteps.length - 1) + panels.length ];
        for ( int i = 0; i < res.length; i++ )
        {
            if ( i < (beforeSteps.length - 1) )
            {
                res[i] = beforeSteps[i];
            } else
            {
                res[i] = panels[i - beforeSteps.length + 1].getComponent().getName();
            }
        }
        return res;
    }
}
